package com.guli.utils;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author ZHAOZHENYU
 * @since 2022/10/2
 */

public class JwtUtils {

    public static final long EXPIRE_TIME = 1000 * 60 * 60 * 24;
    public static final String APP_SECRET = "guli-secret";

    /**
     * 生成token
     * @param id
     * @param nickname
     * @return
     */
    public static String getJwtToken(String id,String nickname){

        String token = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setSubject("guli-user")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE_TIME))
                .claim("id",id)
                .claim("nickname",nickname)
                .signWith(SignatureAlgorithm.HS256,APP_SECRET)
                .compact();
        return token;

    }

    /**
     * 通过token  验证token是否有效
     * @param jwtToken
     * @return
     */
    public static boolean checkToken(String jwtToken){

        if (StringUtils.isEmpty(jwtToken)) return false;

        try {
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 通过 请求头  验证token是否有效
     * @param request
     * @return
     */
    public static boolean checkToken(HttpServletRequest request){

        try {
            String jwtToken = request.getHeader("token");
            if (StringUtils.isEmpty(jwtToken)) return false;
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 通过 请求头  根据token获取会员id
     * @param request
     * @return
     */
    public static String getMemberIdByJwtToken(HttpServletRequest request){
        String jwtToken = request.getHeader("token");
        if (StringUtils.isEmpty(jwtToken)) return "";
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        Claims claims = claimsJws.getBody();
        return (String) claims.get("id");
    }


}
